package com.shyt.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.shyt.dao.LoginTokenVo;
import com.shyt.dao.SysUserVo;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Map;


/***
 * 登录成功处理返回，把用户信息进行返回处理
 */
@Component
@Slf4j
public class LoginSuccessUtil implements AuthenticationSuccessHandler {
    @Autowired
    JwtUtils jwtUtils;
    @Value(value = "${jwt.expiration}")
    private String expiration;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication)
            throws IOException, ServletException {
        log.info("进入登陆成功处理,登陆成功处理开始__________________________________");

        httpServletResponse.setContentType("application/json;charset=utf-8");
        SysUserVo sysUserVo = (SysUserVo) authentication.getPrincipal();

        String token = jwtUtils.generateToken(sysUserVo);//生成了token

        //设置jwt秘钥以及过期时间
        long gqsj = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())//设置签名秘钥
                .parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();//设置过期时间


        SimpleDateFormat sdf18 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = sdf18.format(gqsj);
        log.info("_________设置最长时间是:{},实际剩余时间是:{},format:{}",expiration,gqsj,format);

        LoginTokenVo loginTokenVo =
                new LoginTokenVo(sysUserVo.getId().toString(),sysUserVo,"200","调用成功",token, String.valueOf(gqsj));

        String result = JSON.toJSONString(loginTokenVo, SerializerFeature.DisableCircularReferenceDetect);

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();

        outputStream.write(StringUtils.isEmpty(result) ? new byte[1] :
                result.getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();

        //删除老的token,如果不是第一次登录的情况，如果不是第一次登录，则要删除老的token信息


        Map<String,String> entries = redisTemplate.opsForHash().entries("tokenSession");
        if (null != entries){
            for(String key: entries.keySet()){
                if (sysUserVo.getUsername().equals(entries.get(key))){
                    redisTemplate.opsForHash().delete("tokenSession",key);
                }
            }
        }

        redisTemplate.opsForHash().put("tokenSession","token_" + token,sysUserVo.getUsername());


        log.info("进入登陆成功处理,登陆成功处理结束__________________________________");
    }
}
